package MainPage;

import java.awt.*;
import javax.sound.sampled.*;
import javax.swing.*;
import java.awt.event.*;
import java.io.File;
import java.io.IOException;
import java.util.Calendar;
import java.util.Date;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.filechooser.FileFilter;





public class firstPage extends JFrame implements ActionListener
{
	  DateUtils currentTime;
      display welcomePage;
      static Toolkit tk;
      Container container;
      Image backgroundPicture1,male,female;
      JButton CalenderButton,EventButton,ProfileButton,setSong,browse,EnterNewEvent;
      Icon buttonIcon;
      Font messageFont ;
      int colorIndex=0,previousMusic=0,messageWidth,messageHeight,charWidth,songPosition;
      static int D_age;
      Timer buttonTimer,stringTimer;
      JPanel clockPanel,detailPanel;
      JLabel musicName,musicPanel,logout;
      String songName="",test,SQL;
      static String name,gend,D_dob,D_address,D_city,D_country,D_gend,firstN,lastN;
      Clip soundClip = null;
      boolean first=true;
      static boolean stopPlayback = false,callFromHere=true;
      static SourceDataLine songSource;
      static AudioFormat songFormat;
      static AudioInputStream song;
      JFileChooser browseFile;
      FileFilter filter1;
      public static enterEvent newEvent;
      public static firstPage first_page;
      


	
      public firstPage()
      {
    	  buttonTimer=new Timer(200,new buttonFontColor());
    	  buttonTimer.start();
  		  stringTimer=new Timer(200,new displaySong());
  		  stringTimer.start();
  		  loadDatabase();
    	  loadImage1();
          loadComponent2();
          newEvent=new enterEvent();
          newEvent.setVisible(false);
          setResizable(false);
          setLocationRelativeTo(null);
      }
      
	  
      public void loadComponent2()
      {
    	  
    	  detailPanel = new JPanel()
    	  {
    		  public void paintComponent(Graphics g) 
              {
    			 messageFont = new Font("Monospaced", Font.PLAIN, 18);
                 super.paintComponent(g);
                 g.setFont(messageFont);
                 g.setColor(Color.white);
                 g.drawString("   Name: ",40,50); 
                 g.drawString("    Age: ",40,80);
                 g.drawString("  D.O.B: ", 40, 110);
                 g.drawString("Address: ", 40, 140);
                 g.drawString("   City: ", 40, 170);
                 g.drawString("Country: ",40,200);
                 g.drawString(name, 150, 50);
                 g.drawString(Integer.toString(D_age), 150, 80);
                 g.drawString(D_dob, 150, 110);
                 g.drawString(D_address, 150, 140);
                 g.drawString(D_city, 150, 170);
                 g.drawString(D_country,150,200);
              }  
    	  };

          detailPanel.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "User", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Dialog", 0, 18)));
          detailPanel.setBackground(new java.awt.Color(129, 118, 101));
          detailPanel.setLayout(null);
    	  
          messageFont = new Font("Monospaced", Font.BOLD, 18);
          logout=new JLabel("Logout");
          logout.setFont(messageFont);
    	  logout.setForeground(Color.red);
    	  logout.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
    	  logout.addMouseListener(new java.awt.event.MouseAdapter() {
        	  public void mouseClicked(java.awt.event.MouseEvent evt) {
        	  logoutMouseClicked(evt);
        	  }
        	  });
          
          messageFont = new Font("Monospaced", Font.BOLD, 28);
          EnterNewEvent=new JButton("EnterNewEvent");
          EnterNewEvent.setIcon(buttonIcon);
          EnterNewEvent.setFont(messageFont);
          EnterNewEvent.setBackground(Color.white);
          EnterNewEvent.addActionListener(this);
    	  CalenderButton=new JButton("   My Calendar");
    	  CalenderButton.setIcon(buttonIcon);
    	  CalenderButton.setFont(messageFont);
    	  CalenderButton.setBackground(Color.white);
    	  CalenderButton.addActionListener(this);
    	  EventButton=new JButton("Upcoming Event");
    	  EventButton.setIcon(buttonIcon);
    	  EventButton.setBackground(Color.white);
    	  EventButton.setFont(messageFont);
    	  EventButton.addActionListener(this);
    	  ProfileButton=new JButton("Update Profile");
    	  ProfileButton.setIcon(buttonIcon);
    	  ProfileButton.setBackground(Color.white);
    	  ProfileButton.setFont(messageFont);
    	  ProfileButton.addActionListener(this);
    	  
    	  CalenderButton.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
    	  EventButton.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
   	      ProfileButton.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
          EnterNewEvent.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
   	      
   	      clockPanel = new JPanel() 
 	      {
             public void paintComponent(Graphics g) 
             {
              messageFont = new Font("Monospaced", Font.BOLD, 28);
              super.paintComponent(g);
              g.drawImage(backgroundPicture1,0, 0, getWidth(), getHeight(),this);
              currentTime=new DateUtils();
              clockControl();
              g.setFont(messageFont);
  		      g.drawString(currentTime.now(), 0, getHeight()/2+7);
             }
           };
           clockPanel.setBackground(Color.white);
    	  
           
           musicPanel = new JLabel();
     	   musicPanel.setLayout(null);
     	   musicPanel.setBackground(Color.getHSBColor(0.8F,10,10));
     	  
           setSong=new JButton("Stop Song");
           setSong.setToolTipText("Press to stop the current running song.");
           setSong.addActionListener(this);
           browse=new JButton("Browse");
           browse.setToolTipText("Press to play song by MyOrganiser's media player.");
           browse.addActionListener(this);
           
           musicName=new JLabel()
           {
        	   public void paintComponent(Graphics g) 
               {
        		  
                  super.paintComponent(g);
                  g.drawString(songName,songPosition,20); 
               }  
           };
           Font messageFont = new Font("Monospaced", Font.BOLD, 14);
           musicName.setFont(messageFont);
           musicName.setBackground(Color.white);
           
           setSong.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
           browse.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
           setSong.setEnabled(false);
           musicPanel.add(setSong).setBounds(160,60,150,30);
           musicPanel.add(browse).setBounds(320,60,100,30);
           musicPanel.add(musicName).setBounds(50,20,400,25);
           
           
    	  welcomePage=new display();
    	  welcomePage.setLayout(null);
    	  
    	  container=getContentPane();
    	  container.add(welcomePage);
    	  welcomePage.add(logout).setBounds(1200,15,80,20);
    	  welcomePage.add(CalenderButton).setBounds(850,55,400,100);
    	  welcomePage.add(EventButton).setBounds(850,158,400,100);
    	  welcomePage.add(ProfileButton).setBounds(850,261,400,100);
    	  welcomePage.add(EnterNewEvent).setBounds(850,364,400,100);
          welcomePage.add(detailPanel).setBounds(250,50,600,415);
    	  welcomePage.add(clockPanel).setBounds(830,0,350,60);
    	  welcomePage.add(musicPanel).setBounds(100,550,500,100);
      }
      public void logoutMouseClicked(java.awt.event.MouseEvent evt)
      {
          firstPage.playAudio2(getClass().getResource("/resource/buttonHit.wav").getFile());
    	  
    	  logout.setForeground(Color.red);
    	  performLogout();
      }
      void performLogout()
      {
    	  logoutPage register_page=new logoutPage()
  		{
  			public String getParameter(String name)
  			{
  		           if (name.equalsIgnoreCase("msg"))
  		           {
  		              return "Local Frame";
  		           }
  		           return null;
  		    }
  		};
  		this.dispose();
  		register_page.setVisible(true);
      }
      public static void main(String[] args) 
   	  {
   	    initialGUI2();
      }
      public static void initialGUI2()
      {
    	 firstPage frame2=new firstPage();
    	 frame2.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    	 
         frame2.setLocationRelativeTo(null);
    	 tk= Toolkit.getDefaultToolkit();
   	     Dimension screensize = tk. getScreenSize ();
   	  
   	     frame2.setSize(screensize.width,screensize.height);
 	     frame2.setTitle("MyOrganizer");
 	     frame2.setVisible(true);
    	  frame2.setResizable(false);
      }
      public void loadDatabase()
      {
    	  
    	  SimpleDateFormat D_format = new SimpleDateFormat("dd-MM-yyyy");
    	  SQL="SELECT * FROM USER_DETAIL WHERE USER_CODE="+userMainPage.userCode;
    	  try {
				userMainPage.rs=userMainPage.stmt.executeQuery(SQL);
				userMainPage.rs.next();
				firstN=userMainPage.rs.getString(2);
				lastN=userMainPage.rs.getString(3);
				name=firstN+" "+lastN;
				gend=userMainPage.rs.getString(4);
				D_age=userMainPage.rs.getInt(5);
				D_dob=D_format.format(userMainPage.rs.getDate(6));
				D_address=userMainPage.rs.getString(7);
				D_city=userMainPage.rs.getString(8);
				D_country=userMainPage.rs.getString(9);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				JOptionPane.showMessageDialog(this,"Retrieve data failed!","Error Message",
		                JOptionPane.ERROR_MESSAGE);
				}
			System.out.println(name+gend+D_age+D_dob);
      }
     public void getPreviousMusic() 
     {
    	songSource.stop();
        stringTimer.stop();
     }
 
	public void loadImage1()
      {
		ImageIcon sideBackground=new ImageIcon(getClass().getResource("/resource/panel2.jpg"));  
		 backgroundPicture1=sideBackground.getImage();
		 
		 ImageIcon maleIcon=new ImageIcon(getClass().getResource("/resource/male.png"));
         male=maleIcon.getImage();
         
         ImageIcon femaleIcon=new ImageIcon(getClass().getResource("/resource/female.png"));
         female=femaleIcon.getImage(); 
         
         buttonIcon = new ImageIcon(getClass().getResource("/resource/arrow.jpg"));
      }
	class display extends JPanel
	{
		public void paintComponent(Graphics g)
		{
			super.paintComponent(g);
			g.drawImage(backgroundPicture1,0, 0, getWidth(), getHeight(),this);
			if (gend.equals("M"))
			{
			    g.drawImage(male,20, 100, 200, 350,this);
			    D_gend="Male";
			}
			else
			{
				g.drawImage(female,20, 100, 200, 350,this);
				D_gend="Female";
			}
		}
	}
	
	public void clockControl()
	{
		Timer clock;
		
		clock=new Timer(1000, null);
		clock.start();
		
		repaint();
	}
	
	private class buttonFontColor implements ActionListener
    {
  	  public void actionPerformed(ActionEvent evt) 
        {
  		  colorIndex++; 
            if (colorIndex > 100)
               colorIndex = 0;
            float hue = colorIndex / 100.0F; 
            CalenderButton.setForeground(Color.getHSBColor(hue,1,1));
            EventButton.setForeground(Color.getHSBColor(hue,1,1));
            ProfileButton.setForeground(Color.getHSBColor(hue,1,1));
            EnterNewEvent.setForeground(Color.getHSBColor(hue,1,1));
  		  repaint();
        }
    }
	private class displaySong implements ActionListener
    {
  	  public void actionPerformed(ActionEvent evt) 
        {
  		  
  		  songPosition+=charWidth; 
  		
            if (songPosition > 350)
            {
               songPosition = -messageWidth;
               
            }
  		  repaint();
        }
    }
	
	 public static class DateUtils
	 {
		  public static final String DATE_FORMAT_NOW = "dd-MM-yyyy HH:mm:ss";

		  public String now() 
		  {
		    Calendar cal = Calendar.getInstance();
		    SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_NOW);
		    return sdf.format(cal.getTime());
		  }
		  public static final String DATE_FORMAT_date = "dd-MM-yyyy";
		  public String date()
		  {
			  Calendar cal2 = Calendar.getInstance();
			  SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_date);
			  return sdf.format(cal2.getTime());
		  }
	 }
	 class ExtensionFileFilter extends FileFilter {
		  String description;

		  String extensions[];

		  public ExtensionFileFilter(String description, String extension) {
		    this(description, new String[] { extension });
		  }

		  public ExtensionFileFilter(String description, String extensions[]) {
		    if (description == null) {
		      this.description = extensions[0];
		    } else {
		      this.description = description;
		    }
		    this.extensions = (String[]) extensions.clone();
		    toLower(this.extensions);
		  }

		  private void toLower(String array[]) {
		    for (int i = 0, n = array.length; i < n; i++) {
		      array[i] = array[i].toLowerCase();
		    }
		  }

		  public String getDescription() {
		    return description;
		  }

		  public boolean accept(File file) {
		    if (file.isDirectory()) {
		      return true;
		    } else {
		      String path = file.getAbsolutePath().toLowerCase();
		      for (int i = 0, n = extensions.length; i < n; i++) {
		        String extension = extensions[i];
		        if ((path.endsWith(extension) && (path.charAt(path.length() - extension.length() - 1)) == '.')) {
		          return true;
		        }
		      }
		    }
		    return false;
		  }
		}
	 
	 public static void playAudio(String file)
	 {
		    try{
		      File soundFile = new File(file);
		      song= AudioSystem. getAudioInputStream(soundFile);
		      songFormat= song.getFormat();
		    //  soundClip = AudioSystem.getClip();
			//    soundClip.open(song);
			//    soundClip.start();

		      DataLine.Info dataLineInfo =
		                          new DataLine.Info(
		                            SourceDataLine.class,
		                                    songFormat);

		      songSource=
		             (SourceDataLine)AudioSystem.getLine(
		                                   dataLineInfo);

		      //Create a thread to play back the data and
		      // start it running.  It will run until the
		      // end of file, or the Stop button is
		      // clicked, whichever occurs first.
		      // Because of the data buffers involved,
		      // there will normally be a delay between
		      // the click on the Stop button and the
		      // actual termination of playback.
		      //songSource.start();
		      new PlayThread().start();
		    }catch (Exception e) {
		      e.printStackTrace();
		    //  System.exit(0);
		    }
		  }

	 
	 static class PlayThread extends Thread{
		  byte tempBuffer[] = new byte[10000];

		  public void run(){
		    try{
		      songSource.open(songFormat);
		      songSource.start();

		      int cnt;
		      //Keep looping until the input read method
		      // returns -1 for empty stream or the
		      // user clicks the Stop button causing
		      // stopPlayback to switch from false to
		      // true.
		      while((cnt = song.read(
		           tempBuffer,0,tempBuffer.length)) != -1
		                       && stopPlayback == false){
		        if(cnt > 0){
		          //Write data to the internal buffer of
		          // the data line where it will be
		          // delivered to the speaker.
		          songSource.write(
		                             tempBuffer, 0, cnt);
		        }//end if
		      }//end while
		      //Block and wait for internal buffer of the
		      // data line to empty.
		      songSource.drain();
		      songSource.close();

		      //Prepare to playback another file
		     
		    }catch (Exception e) {
		      e.printStackTrace();
		      System.exit(0);
		    }//end catch
		  }//end run
		}//end inner class PlayThread
		//===================================//

	 public static void playAudio2(String file)
	 {
		    try{
		      File soundFile = new File(file);
		      song= AudioSystem. getAudioInputStream(soundFile);
		      songFormat= song.getFormat();


		      DataLine.Info dataLineInfo =
		                          new DataLine.Info(
		                            SourceDataLine.class,
		                                    songFormat);

		      songSource=
		             (SourceDataLine)AudioSystem.getLine(
		                                   dataLineInfo);

		      new PlayThread2().start();
		    }catch (Exception e) {
		      e.printStackTrace();
		    }
		  }

	 
	 static class PlayThread2 extends Thread{
		  byte tempBuffer[] = new byte[10000];

		  public void run(){
		    try{
		      songSource.open(songFormat);
		      songSource.start();

		      int cnt;

		      while((cnt = song.read(
		           tempBuffer,0,tempBuffer.length)) != -1
		                       && stopPlayback == false){
		        if(cnt > 0){
		          songSource.write(
		                             tempBuffer, 0, cnt);
		        }
		      }
		      songSource.drain();
		      songSource.close();
		     
		    }catch (Exception e) {
		      e.printStackTrace();
		      System.exit(0);
		    }
		  }
		}
	 
	public void updateProfile()
	{
		userDetails profile_page=new userDetails()
			{
				public String getParameter(String name)
				{
			           if (name.equalsIgnoreCase("msg"))
			           {
			              return "Local Frame";
			           }
			           return null;
			    }
			};
			profile_page.setSize(userMainPage.screensize.width,userMainPage.screensize.height);
			this.setVisible(false);
			userDetails.fnameTextField.setText(firstN);
			userDetails.lnameTextField.setText(lastN);
			userDetails.ageTextField.setText(Integer.toString(D_age));
			userDetails.addressTextArea.setText(D_address);
			userDetails.cityTextField.setText(D_city);
			userDetails.DOBTextField.setText(D_dob);
			userDetails.countryTextField.setText(D_country);
			userDetails.genderTextField.setText(gend);
			userDetails.usernameTextField.setText(userMainPage.user_name);
			userDetails.jPasswordField1.setText(userMainPage.user_password);
			profile_page.setVisible(true);
	}
	public void myCalendar()
	{
		calendarGUI calender_page=new calendarGUI()
		{
			public String getParameter(String name)
			{
		           if (name.equalsIgnoreCase("msg"))
		           {
		              return "Local Frame";
		           }
		           return null;
		    }
		};
		callFromHere=true;
		//calender_page.setSize(userMainPage.screensize.width,userMainPage.screensize.height);
		calender_page.setVisible(true);
	}
	public void checkUp()
	{
		checkUpcomingEvent check_page=new checkUpcomingEvent()
		{
			public String getParameter(String name)
			{
		           if (name.equalsIgnoreCase("msg"))
		           {
		              return "Local Frame";
		           }
		           return null;
		    }
		};
		this.dispose();
		check_page.setVisible(true);
	}
	public void actionPerformed(ActionEvent evt) 
	{
		
		String command = evt.getActionCommand();
		if (command.equals("Stop Song"))
		{
			getPreviousMusic();
		}
		if (command.equals("Browse"))
		{
			
			browseFile=new JFileChooser(".");
			filter1 = new ExtensionFileFilter("WAV, AU", new String[] { "WAV", "AU" });
		    browseFile.setFileFilter( filter1);
			int returnVal = browseFile.showOpenDialog(firstPage.this);
            
	        if (returnVal == JFileChooser.APPROVE_OPTION)
	        {
	        	if(!first)
					getPreviousMusic() ;
	        	
	            File selectedFile = browseFile.getSelectedFile();
	            playAudio(selectedFile.getPath());
	            songName=selectedFile.getName();
	        } 
	        first=false;
			FontMetrics fm = getFontMetrics(messageFont);
	        messageWidth = fm.stringWidth(songName);
	        charWidth = fm.charWidth('H');
	        songPosition=-messageWidth;
	        stringTimer.restart();
	        setSong.setEnabled(true);
		}
		if (command.equals("Update Profile"))
		{
			updateProfile();
		}
		if (command.equals("Upcoming Event"))
		{
			checkUp();
		}
		if (command.equals("   My Calendar"))
		{
			first_page=new firstPage();
			first_page.setVisible(false);
			callFromHere=true;
			this.dispose();
			myCalendar();
		}
		if (command.equals("EnterNewEvent"))
		{
			this.dispose();
			callFromHere=false;
			newEvent.setVisible(true);
		}
		repaint();
	}
}

